package com.ygsoft.activiti.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ygsoft.activiti.eunm.ActivitProccessEnum;
import com.ygsoft.activiti.model.MyModel;
import com.ygsoft.activiti.model.MyProcess;
import com.ygsoft.activiti.model.TaskModel;
import com.ygsoft.activiti.service.RespositoryServiceInf;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 关于模型的默认实现类
 * activiti 中 流程模型的创建，设置，删除  流程的 部署和挂起等
 * @author zhx
 * @create 2017-11-13 15:11
 **/

@Component
public class RespositoryServiceImpl implements RespositoryServiceInf {
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private HistoryService historyService;


    @Override
    public boolean delProcessId(String processId) {
        return false;
    }


    @Override
    public List<TaskModel> getAllTaskModel(String processId) {
        //获取流程定义的实例
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(processId);
        //获取流程定义的任务节点
        Map<String, TaskDefinition> taskDefinitions = definitionEntity.getTaskDefinitions();

        List<TaskModel> taskModels = new ArrayList<>();

        //循环输出任务节点
        for(Map.Entry<String, TaskDefinition> entry : taskDefinitions.entrySet()){
            TaskModel taskModel = new TaskModel();

            taskModel.setKey(entry.getKey());;

            TaskDefinition value = entry.getValue();

            taskModel.setName(value.getNameExpression().getExpressionText());
            taskModel.setRoleLists(null);
            taskModel.setUserIds(null);

            taskModels.add(taskModel);
        }
        return taskModels;
    }

    @Override
    public boolean deleteModel(String modelId) {
        try {
            repositoryService.deleteModel(modelId);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String getProcessXML(String processId) {
        String resXML = "";
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            String deployId = processDefinition.getDeploymentId();
            //获取 xml资源文件名
            String XMLResource = processDefinition.getResourceName();
            InputStream resourceAsStream = repositoryService
                    .getResourceAsStream(deployId, XMLResource);
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] bpmnByte = new byte[1024];
            int len = -1;
            while ((len = resourceAsStream.read(bpmnByte, 0, 1024)) != -1) {
                outSteam.write(bpmnByte, 0, len);
            }
            //首先把String转换为ISO-8859-1，然后在前端用UTF-8显示
            resXML =  new String(outSteam.toString().getBytes("UTF-8"),"ISO-8859-1");
            return resXML;
        }catch (Exception e){
            e.printStackTrace();
            return resXML;
        }
    }

    @Override
    public boolean deployModel(String modelId) {
        //System.out.println(modelId);
        try {
            //获取指定模型id的模型
            Model modelData = repositoryService.getModel(modelId);
            //解析模型
            ObjectNode modelNode = (ObjectNode) new ObjectMapper()
                    .readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte [] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            //部署
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .addString(processName,new String(bpmnBytes, "utf-8"))
                    .deploy();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String createModel(String name, String key, String description) throws UnsupportedEncodingException {
        try{
            //将前端 ISO-8859-1编码转码为 UTF-8
            name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
            key = new String(key.getBytes("ISO-8859-1"),"UTF-8");
            description = new String(description.getBytes("ISO-8859-1"),"UTF-8");
            //创建一个activiti bpmn模板对象
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id","canvas");
            editorNode.put("resourceId","canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace","http://b3mn.org/stencilset/bpmn2.0#");
            //为模型绑定参数
            editorNode.put("stencilset",stencilSetNode);
            //创建模型对象
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME,name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION,1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION,description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            //保存模型模型
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(),editorNode.toString().getBytes("utf-8"));

            return modelData.getId();
        }catch(Exception e){
            throw e;
        }
    }


    @Override
    public BufferedImage getProcessImg(String processId) {
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            String deployId = processDefinition.getDeploymentId();
            //获取流程定义的图片资源名
            String ImgResource = processDefinition.getDiagramResourceName();
            //根据部署id、资源名 查询图片二进制流
            InputStream imageStream = repositoryService.getResourceAsStream(deployId, ImgResource);
            BufferedImage bufferedImage = ImageIO.read(imageStream);
            return bufferedImage;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Date: 16:51 2017/6/2
     * 获取指定流程进度追踪图
     */
    @Override
    public String getProgressImg(String processInstanceId) {
        HistoricProcessInstance processInstance =  historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
//获取流程图

        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());


        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity)repositoryService
                .getProcessDefinition(processInstance.getProcessDefinitionId());

        Map<String, TaskDefinition> taskDefinitions = definitionEntity.getTaskDefinitions();


        for(Map.Entry<String, TaskDefinition> entry : taskDefinitions.entrySet()){
            System.out.print("Key = "+entry.getKey());

            TaskDefinition value = entry.getValue();
        }

        List<HistoricActivityInstance> highLightedActivitList =  historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity,highLightedActivitList);
        for(HistoricActivityInstance tempActivity : highLightedActivitList){
            String activityId = tempActivity.getActivityId();
            highLightedActivitis.add(activityId);
        }
        //中文显示的是口口口，设置字体就好了
        InputStream imageStream = new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, "宋体", "宋体","宋体", null, 1.0);
        byte[] result = null;
        try {
            result = new byte[imageStream.available()];
            imageStream.read(result);
            imageStream.close();
        } catch (IOException e) {

        }
        return new BASE64Encoder().encode(result);
    }

    //    }
//
    @Override
    public List<MyModel> getAllModule() {
        List<MyModel> resList = new ArrayList<MyModel>();
        try {
            //获取所有模型列表
            List<Model>list = repositoryService.createModelQuery().orderByCreateTime()
                    .desc().list();
            for (Model model : list) {
                //转换为前端显示MyModel
                MyModel myModel = new MyModel(model);
                resList.add(myModel);
            }
            return resList;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return resList;
        }
    }

    @Override
    public boolean deleteDeployment(String deployId) {
        try{
            repositoryService.deleteDeployment(deployId,true);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int changeProcessStatus(String processId) {
        try{
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            //激活流程 1
            if(processDefinition.isSuspended()){

                repositoryService.activateProcessDefinitionById(processId);
                return ActivitProccessEnum.UNSUSPEND.getStatus();
            }
            //挂起流程 2
            else{
                // 此处为按ID挂起，同时挂起所有与流程相关,立刻挂起
                repositoryService.suspendProcessDefinitionById(processId);
                return ActivitProccessEnum.SUSPEND.getStatus();
            }
        }catch (Exception e){
            e.printStackTrace();
            return ActivitProccessEnum.ERRORSTATUS.getStatus();
        }
    }

    @Override
    public List<MyProcess> getAllProcess() {
        List<MyProcess> resList = new ArrayList<MyProcess>();
        try {
            List<ProcessDefinition>list = repositoryService.createProcessDefinitionQuery()
                    .orderByProcessDefinitionId().asc().list();
            for (ProcessDefinition process : list) {
                MyProcess myProcess = new MyProcess(process);
                resList.add(myProcess);
            }
            return resList;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }


    /**
     * @Date: 16:55 2017/6/2
     * 获取需要高亮的线id
     */
    private List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity, List<HistoricActivityInstance> historicActivityInstances) {
        // 用以保存高亮的线flowId
        List<String> highFlows = new ArrayList<String>();
        // 对历史流程节点进行遍历// 得到节点定义的详细信息
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());
            // 用以保存后需开始时间相同的节点
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                // 后续第一个节点
                HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j);
                // 后续第二个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1);
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            // 取出节点的所有出去的线
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }

}
